#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <strings.h>
#include "Logger.hpp"

static const int gdefaultsockfd = -1;
class UdpServer
{
public:
    UdpServer(uint16_t port) : _sockfd(gdefaultsockfd), _port(port), _isrunning(false)
    {
    }
    void Init()
    {
        // 1.创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0); //  把网络在文件系统中展开
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "create socket error";
            exit(1);
        }
        LOG(LogLevel::INFO) << "create socket success: " << _sockfd;

        // 2.bind套接字
        // 2.1 填充IP和Port
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port); // 统一大端

        // local.sin_addr.s_addr = inet_addr(_ip.c_str()); // inet_addr 1. 字符串转整数ip 2. 整数ip是网络序列的

        local.sin_addr.s_addr = htonl(INADDR_ANY); // 任意IPbind  不明确具体IP，只要发给对应的主机，对应的port，全都能收到
        // 2.2 和socketfd进行bind
        int n = bind(_sockfd, (const sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind socket error";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind socket success : " << _sockfd;
    }
    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            // 读取数据
            char buffer[1024];
            buffer[0] = 0; //  O(1) 清空数据
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&peer, &len); // flag == 0 , 阻塞模式
            if (n > 0)
            {
                uint16_t clientport = ntohs(peer.sin_port);
                std::string clientip = inet_ntoa(peer.sin_addr);

                buffer[n] = 0;
                LOG(LogLevel::DEBUG) << "[" << clientip << " : " << clientport << "]#" << buffer;

                std::string echo_string = "server echo# ";
                echo_string += buffer;
                sendto(_sockfd, echo_string.c_str(), echo_string.size(), 0, (struct sockaddr *)&peer, len);
            }
        }
        _isrunning = false;
    }
    void Stop()
    {
        _isrunning = false;
    }
    ~UdpServer()
    {
    }

private:
    int _sockfd;
    uint16_t _port;
    // std::string _ip; // 不建议绑定固定ip

    bool _isrunning;
};